# -*- coding: UTF-8 -*-
#suppress 'too many' lines warning
#pylint: disable-msg=C0302

"""
copyright (c) 2009, paketka@gmail.com et. al
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

    * Neither the name of the <ORGANIZATION> nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import datetime
import calendar
import math

from django.shortcuts import render_to_response, get_object_or_404
from django.shortcuts import get_list_or_404
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.http import Http404
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.cache import cache_page

#suppress wildcard import warning
#pylint: disable-msg=W0401
#suppress unused symbol from wildcard import
#pylint: disable-msg=W0614
from psp.models import *
#suppress wildcard import warning
#pylint: disable-msg=W0401
from GChartWrapper import *
#suppress wildcard import warning
#pylint: disable-msg=W0401
from utils.charts import *
from justice.views import getAuthToken


def create_range_data(date, rangeType):
    """
    Function get_range_data(date, rangeType)

    Accepts two mandatory arguments a date object and rangeType, which is a
    string.  The expected values for range type are as follows:
        den     for day
        tyden   for week
        mesic   for month

    Returns a dictionary below:
        {
            'dateStart' :   datetime object
            'dateEnd'   :   datetime object
            'viewTitle' :   unicode string
            'tabIndex'  :   integer
            'chartTitle' :  unicode string
        }
    The data from dictinary are meant to be passed to .html templates
    """
    rangeType = rangeType.lower()
    retVal = None

    if rangeType == 'den':
        retVal = {}
        retVal['viewTitle'] = _(u'Denní přehled za ') +\
            date.strftime('%d. %B %Y')
        retVal['dateStart'] = date
        retVal['dateEnd'] = None
        retVal['tabIndex'] = 0
        retVal['chartTitle'] = date.strftime("%d. %b %Y")
    elif rangeType == 'tyden':
        retVal = {}
        #suppress unused variable wd warning
        #pylint: disable-msg=W0612
        (year, week, wd) = date.isocalendar()
        retVal['viewTitle'] = \
            _(u'Týdenní přehled za %d. týden %d') % (week, year)
        td = datetime.timedelta(days = date.weekday())
        retVal['dateStart'] = date - td
        td = datetime.timedelta(days = 6 - date.weekday())
        retVal['dateEnd'] = date + td
        retVal['tabIndex'] = 1
        retVal['chartTitle'] = _(u'%d. Týden %d') % (week, year)
    elif rangeType == 'mesic':
        retVal = {}
        retVal['viewTitle'] = \
            _(u'Měsíční přehled za ') + date.strftime('%B %Y')
        retVal['dateStart'] = datetime.date(
                day = 1,
                month = date.month,
                year = date.year
            )
        #suppress unused variable wd warning
        #pylint: disable-msg=W0612
        first, last = calendar.monthrange(
                            year = date.year,
                            month = date.month
                    )
        retVal['dateEnd'] = datetime.date(
                day = last,
                month = date.month,
                year = date.year
            )
        retVal['tabIndex'] = 2
        retVal['chartTitle'] = date.strftime('%B %Y')

    return retVal


def cmp_surname(a, b):
    """
    Function cmp_surname(a, b)

    Compares two MP objects by surname. Mandatory arguments a, b
    are instaces of Person class.
    """
    if a.surname < b.surname:
        return -1
    elif a.surname > b.surname:
        return 1
    else:
        return 0


def get_recyclation_chart(terms):
    """
    Function get_recyclation_chart(terms)

    Renders a bar chart showing a percentage of recycled MPs (MPs who
    are serving for more than one electoral term) in each term.

    The mandatory argument terms is a list of psp.models.TermOfOffice
    instances.  The resulting chart will have a bar for each single term.

    Returns an instance of GChartWrapper.VerticalBarGroup on success,
    otherwise exception is thrown (?IndexError?)
    """
    termStats = range(terms.count())
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    qs = Person.objects.all()

    for mp in qs:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        elects = Membership.objects.filter(
                    person = mp,
                    group__type__exact = 'PARLAMENT',
                    post__iregex = '.*POSLAN.*'
                ).count()
        if elects > 0:
            elects -= 1
            try:
                termStats[elects] += 1
            except:
                import pdb;pdb.set_trace()
                print '%s %s' % (mp.name, mp.surname)
                #suppress 'no objects member' warning
                #pylint: disable-msg=E1101
                for e in Membership.objects.filter(
                    person = mp,
                    group__type__exact = 'PARLAMENT',
                    post__iregex = '.*POSLAN.*'
                ):
                    print '%s' % e.post
                    print e.start, '-', e.end
                raise
    count = qs.count()
    
    gData = []
    for t in termStats:
        i = ((1.0 * t) / count) * 100.0
        gData.append(i)

    chart = VerticalBarGroup(gData)
    chart.color('777777')
    s = ''
    for i in range(terms.count()):
        s += str(i) + '|'

    
    chart.title(_(u'Recyklace [%]'))

    chart.axes.type('xxyt')
    chart.axes.label(0, s)
    chart.axes.label(1, u'', u'', _(u'počet recyklací'))
    chart.axes.label(2, get_axis(range(0, 100, 20)) + u'%')
    chart.axes.label(3, get_axis(termStats))

    return chart


def get_recyclation_for_term(term):
    """
    Function get_recyclation_for_term(term)

    Retrieves data for recyclation pie chart for given term.

    The mandatory argument term is an instance of psp.models.TermOfOffice
    class, which defines a particular electoral term we want to render chart
    for.

    Returns tupp,   <-> percent of MPs, who were recycled
        recycled,   <-> percent of MPs, who are new
        freshmen    <-> absolute number of new MPs
        zombies,    <-> absolute number of recycled MPs
        greenhorns  <-> percent of new MPs
    )
    """
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    mpsInTerm = Person.objects.getPersonsOrderByName(term = term)
    recycled = 0
    zombies = 0
    freshmen = 0
    greenhorns = 0
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    if term == TermOfOffice.objects.all()[0]:
        recycled = 0
        zombies = 0
        freshmen = 100.0
        greenhorns = len(mpsInTerm)
    else:
        zombies = 0
        for mp in mpsInTerm:
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            mpMembership = Membership.objects.filter(
                                person = mp,
                                group__type__exact = 'PARLAMENT',
                                post__iregex = '.*POSLAN.*'
                            )
            if mpMembership.count() > 1:
                zombies += 1
    
        recycled = get_percents(zombies, len(mpsInTerm))
        freshmen = 100.0 - recycled
        greenhorns = len(mpsInTerm) - zombies

    return recycled, freshmen, zombies, greenhorns
    

def get_recycled_pie_chart(term):
    """
    Function get_recycled_pie_chart(term)

    Function renders pie chart, which presents the ratio between fresh MPs and
    recycled MPs in given term. The term argument is an instance of
    psp.models.TermOfOffice class.

    Returns an instance of Pie3D class.
    """
    recycled, freshmen, zombies, greenhorns = get_recyclation_for_term(term)
    retVal = Pie3D([ recycled / 100.0, freshmen / 100.0 ])
    retVal.label(
            _(u'Veteráni') + ' %d' % int(zombies),
            _(u'Zelenáči') + ' %d' % int(greenhorns)
        )
    retVal.color('005500', '00aa00') 

    yearStart = term.yearStart
    yearEnd = term.yearEnd
    if yearEnd == '':
        yearEnd = str(datetime.datetime.today().year)
    retVal.title(
        _(u'Zelenáči vs. Veteráni') + '(%s - %s)' % (yearStart, yearEnd)
    )

    retVal.size(330, 130)

    return retVal


def get_recyclation_trend_chart(terms):
    """
    Function get_recyclation_trend_chart(terms)

    Function renders a bar chart. Each bar represents a ratio between new and
    recycled MPs in given term. The mandatory argument terms is list of
    psp.models.TermOfOffice instances. Each term object from list will
    'generate' a vertical bar in final chart.

    Returns instance of GChartWrapper.VerticalBarStack.
    """
    recycled = []
    freshmen = []
    absRecycled = []
    recycled.append(0.0)
    freshmen.append(100.0)
    absRecycled.append(0)
    for t in terms[1:]:
        #suppress unused variable wd warning
        #pylint: disable-msg=W0612
        recycld, frshmn, zombies, greenhorns = get_recyclation_for_term(t)
        absRecycled.append(zombies)
        recycled.append(recycld)
        freshmen.append(frshmn)

    chart = VerticalBarStack([recycled, freshmen])
    chart.title(_(u'Recyklační trend'))
    chart.color('005500', '00AA00')
    chart.legend(_(u'Veteráni'), _(u'Zelenáči'))
    chart.axes.type('xxty')
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(absRecycled))
    chart.axes.label(3, get_axis(range(0, 100, 20)) + u'%')

    return chart


def get_mf_ratio_chart(terms):
    """
    Function get_mf_ratio_chart(terms)

    Renders a vertcal bars chart representing the ratio between number of
    MP-ladies and MP-gentlemen in each term. The mandatory argument terms
    is list of psp.models.TermOfOffice instances, each instance is a term we
    want to generate vertical bar for.

    Returns instance of GChartWrapper.VerticalBarStack
    """
    termStats = []
    females = []
    males = []

    for t in terms:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        g = Group.objects.get(type__iexact = 'PARLAMENT', term = t)
        male, female = g.getMfRatio()
        pm = get_percents(male, male + female)
        pf = get_percents(female, male + female)
        males.append(pm)
        termStats.append(pf)
        females.append(female)

    chart = VerticalBarStack([females, males])
    chart.title(_(u'Počet žen v parlamentu'))
    chart.color('770000', '000077')
    chart.legend(_(u'Ženy'), _(u'Muži'))
    chart.axes.type('xxyt')
    
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(range(0, 100, 20)) + u'%')
    #suppress used builtin function 'map' warning
    #pylint: disable-msg=W0141
    chart.axes.label(3, get_axis( map(lambda f: "%d" % int(f), females) ))

    return chart


def get_mp_orgs_chart(terms):
    """
    Function get_mp_orgs_chart(terms)

    Renders a chart of vertical bars, each bar represents the number of
    different groups (committees, boards, etc.) in parliament in each term.
    The mandatory argument terms is a list of psp.models.TermOfOffice instaces.

    Returns GChartWrapper.VerticalBarGroup obejct
    """
    termStats = []

    for t in terms:
        termStats.append(
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            Group.objects.filter(term = t).count()
        )
    
    maxGroupCount = max(termStats)
    yRange = ((maxGroupCount / 20) + 1) * 20
    #suppress used builtin function 'map' warning
    #pylint: disable-msg=W0141
    bars = map(lambda x: (x * 1.0 / yRange) * 100.0, termStats)
    chart = VerticalBarGroup(bars)
    chart.color('777777')
    chart.title(_(u'Počet parl. organizací'))
    chart.axes.type('xxyt')
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(range(0, yRange, 40))) 
    chart.axes.label(3, get_axis(termStats)) 

    return chart


def get_avg_age_chart(terms):
    """
    Function get_avg_age_chart(terms)

    Renders chart made of vertical bars. Each bar represents the average
    MP age for particular term. The mandatory argument terms is list of
    psp.models.TermOfOffice instances.

    Returns GChartWrapper.VerticalBarGroup object
    """
    avgAges = []

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    for parlament in Group.objects.filter(type__iexact = 'PARLAMENT'):
        avgAges.append(parlament.getAvgAge())

    maxAvg = max(avgAges)
    yRange = ((maxAvg / 10) + 1) * 10
    #suppress used builtin function 'map' warning
    #pylint: disable-msg=W0141
    chart = VerticalBarGroup(map(lambda x: ((x * 1.0)/yRange) * 100.0, avgAges))
    chart.color('777777')
    chart.title(_(u'Prům. věk'))
    chart.axes.type('xxyt')
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(range(0, yRange, 10))) 
    chart.axes.label(3, get_axis(avgAges)) 

    return chart


def get_absences_chart(terms):
    """
    Function get_absences_chart(terms)

    Renders a vertical bar chart representing MP absences. There
    is drawn a single bar for each term. The mandatory argument
    terms is list of psp.models.TermOfOffice instances.

    Returns GChartWrapper.VerticalBarStack instance
    """
    absences = []
    presences = []
    for t in terms:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        voteStats = VoteStats.objects.getStatsForTerm(t)
        perc = get_percents(    voteStats.totalAbsences,
                                voteStats.presences
                        )
        absences.append(math.ceil(perc))
        presences.append(100 - math.floor(perc))

    chart = VerticalBarStack([absences, presences])
    chart.color('770000', '007700')
    chart.legend(_(u'Chybí'), _(u'Přítomno'))
    chart.title(_(u'Absence při hlasování [%]'))
    chart.axes.type('xxty')
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(absences)) 

    return chart


def get_avg_groups(terms):
    """
    Function get_avg_groups(terms)

    Calculates the average number of groups each MP is member of.  The
    mandatory argument terms is list of psp.models.TermOfOffice instances we
    want to aggregate.
    
    Returns integer
    """
    mpsInTerm = 0
    memberships = 0
    for t in terms:
        date = None
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        groups = Group.objects.filter(term = t)

        for g in groups:
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            memberships += Membership.objects.filter(
                                                    group = g,
                                                    post__iregex = '.len'
                                                ).count()

        date = None
        if t.isComplete():
            date = datetime.date(
                    year = t.getStart() + (t.getStart() - t.getEnd() / 2),
                    month = 2,
                    day = 15
                )
        else:
            date = datetime.date.today()

        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        mpsInTerm += Person.objects.countPersonsForDay(date)

    return memberships / mpsInTerm
        

def get_avg_groups_chart(terms):
    """
    Function get_avg_groups(terms)

    Renders a chart showing the average number of groups each MP is
    participating in. The mandatory argument terms is a list of
    psp.models.TermOfOffice instances.

    Returns GChartWrapper.VerticalBarGroup instance
    """
    groupStats = []

    for t in terms:
        date = None
        memberships = 0
        mpsInTerm = 0

        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        for g in Group.objects.filter(term = t):
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            memberships += Membership.objects.filter(group = g).count()

        if t.isComplete():
            date = datetime.date(
                    year = t.getStart() + ((t.getEnd() - t.getStart()) / 2),
                    month = 2,
                    day = 15
                )
        else:
            date = datetime.date.today()

        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        mpsInTerm += Person.objects.countPersonsForDay(date)

        avgGroups = (memberships * 1.0) / (mpsInTerm)
        groupStats.append(avgGroups)

    yRange = ((max(groupStats) / 10) + 1) * 10
    #suppress used builtin function 'map' warning
    #pylint: disable-msg=W0141
    chart = VerticalBarGroup(map(lambda x: (x/yRange) * 100.0, groupStats))
    chart.color('777777')
    chart.title(_(u'Skupin na poslance'))
    chart.axes.type('xxytt')
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(range(0, int(yRange), 5000))) 

    evenGroups = ['%.2f' % groupStats[i]
                            for i in range(len(groupStats)) if i % 2 == 0
                ]
    oddGroups =  ['%.2f' % groupStats[i]
                            for i in range(len(groupStats)) if i % 2 == 1
                ]
    chart.axes.label(3, get_axis(evenGroups, 1, 0)) 
    chart.axes.label(4, get_axis(oddGroups, 1, 1)) 

    return chart


def get_poll_count_chart(terms):
    """
    Function get_poll_count_chart()

    Renders a chart of vertical bars, each bar represents a total number of polls
    in given term. The mandatory argument terms is list of
    psp.models.TermOfOffice instances.

    Returns GChartWrapper.VerticalBarGroup instance.
    """
    pollStats = []

    for t in terms:
        polls = 0
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        for m in Meeting.objects.filter(term = t):
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            polls += Poll.objects.filter(meeting = m).count()
        pollStats.append(polls)

    maxPollsCount = max(pollStats)
    yRange = ((maxPollsCount / 1000) + 1) * 1000
    chart = VerticalBarGroup(
        #suppress used builtin function 'map' warning
        #pylint: disable-msg=W0141
        map(lambda x: ((x * 1.0)/yRange) * 100.0,
        pollStats)
    )
    chart.color('777777')
    chart.title(_(u'Počet hlasování'))
    chart.axes.type('xxytt')
    startY, endY = get_year_rng_axes(terms)
    chart.axes.label(0, startY)
    chart.axes.label(1, endY)
    chart.axes.label(2, get_axis(range(0, yRange, 5000))) 

    evenPolls = [pollStats[i] for i in range(len(pollStats)) if i % 2 == 0]
    oddPolls =  [pollStats[i] for i in range(len(pollStats)) if i % 2 == 1]
    chart.axes.label(3, get_axis(evenPolls, 1, 0)) 
    chart.axes.label(4, get_axis(oddPolls, 1, 1)) 

    return chart

    
def get_party_age(term):
    """
    Function get_party_age(term)

    Renders chart made of vertical bars. Each bar represents the average age of
    party club. The mandatory argument term is instance of
    psp.models.TermOfOffice class.

    Returns instance of GChartWrapper.VerticalBarGroup class.
    """
    records = []
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    for club in Group.objects.filter(type__iexact = 'KLUB', term = term):
        record = {}
        record['club'] = club
        record['avgAge'] = club.getAvgAge()
        records.append(record)
        
    gData = []
    colors = []
    for i in records:
        gData.append([ i['avgAge'] ])

    #suppress used builtin function 'map' warning
    #pylint: disable-msg=W0141
    chart = VerticalBarGroup(map(lambda x: x['avgAge'], records))
    chart.scale(0, 100)
    colors = ''
    for i in records:
        colors += i['club'].color + '|'
    chart.color(colors.strip('|'))
    chart.title(u'Průměrný věk stranických klubů')
    evenParties = [
        records[i]['club'].getPartyName()
        for i in range(len(records)) if i % 2 == 0
    ]
    oddParties = [
        records[i]['club'].getPartyName()
        for i in range(len(records)) if i % 2 == 1
    ]
    chart.axes.type('xxyt')
    chart.axes.label(0, get_axis(evenParties, 1, 0))
    chart.axes.label(1, get_axis(oddParties, 1, 1))
    chart.axes.label(2, get_axis(['0', '20', '40', '60', '80']))
    ages = [ '%.2f' % i['avgAge'] for i in records ]
    #suppress warning complaining about using *ages as argument
    #pylint: disable-msg=W0142
    chart.axes.label(3, *ages)

    return chart


def show_mp(request, mpSlug):
    """
    Function show_mp(request, mpSlug)

    Implements a django view method for particular MP. Function renders a HTML
    page from mp_all_terms_tab.html. The page lists all functional (office)
    terms for given MP. There are two mandatory argumetns:
        request -   instance of django.http.HttpRequest class
        mpSlug  -   string with slug grabbed from url (i.e. josef_novak)
    The function uses mp_all_terms_tab.html template.

    Returns instance django.http.HttpResponse class
    """
    termData = []
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    terms = TermOfOffice.objects.all()
    term = None
    mp = None
    for t in terms:
        #suppress 'Exception does not do anything' warning
        #pylint: disable-msg=W0704
        try:
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            mp = Person.objects.getPerson(mpSlug.lower(), term = t)
            presenceChart = mp.votes.getPresenceChart()
            presenceChart.size(330, 80)
            formStrData = (mp.name, mp.surname, t.getStart(), t.getEnd())
            presenceChart.title(_(u'Absence %s %s (%s %s)' % formStrData))
            record = {
                'term' : t,
                'mp' : mp,
                'presenceChart' : presenceChart,
                'parties' : mp.getPartyMships(t),
            }
            termData.append(record)
            term = t
        except ObjectDoesNotExist:
            pass

    if mp == None:
        raise Http404

    mships = mp.getParlMemberships()
    mships = mships.order_by('start')
    
    if len(termData) == 0 or mships.count() == 0:
        raise Http404

    dateStart = mships[0].start
    dateEnd = None
    
    if mships.filter(end = None).count() != 0:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        dateEnd = Poll.objects.all().order_by('-date')[0].date
    else:
        mships = mships.order_by('-end')
        dateEnd = mships[0].end

    return render_to_response(
        'mp_all_terms_tab.html',
        {   'tabIndex' : 4,
            'termRecords' : termData,
            'mp' : mp,
            'justiceKey' : getAuthToken(unicode(mp.name) + unicode(mp.surname)),
            'terms' : mp.getTermLinks(),
            'dateStart' : dateStart,
            'dateEnd' : dateEnd,
            'date' : dateEnd,
            'term' : term,
        },
        context_instance = RequestContext(request)
    )


@cache_page(60 * 60 * 24)
def all_terms_tab(request):
    """
    Function all_terms_tab(request)

    Implements django's view for default page (something like index.html).  By
    default it renders a day overview for the last meeting day in parliament.
    Accepts on mandatory argument request, which is an instance of
    django.http.HttpRequest class. The function uses all_terms.html template.

    Returns django.HttpResponse object.
    """
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    terms = TermOfOffice.objects.all()
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dateStart = Poll.objects.all().order_by('date')[0].date
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dateEnd = Poll.objects.all().order_by('-date')[0].date

    return render_to_response(
        'all_terms.html',
        {   'dateStart' : dateStart,
            'dateEnd' : dateEnd,
            'date' : dateEnd,
            'tabIndex' : 4,
            'firstYear' : terms[0].getStart(),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'totalPolls' : Poll.objects.all().count(),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'totalMeetings' : Meeting.objects.all().count(),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'mpTotal' : Person.objects.all().count(),
            'recycle' : get_recyclation_chart(terms),
            'recycleTrend' : get_recyclation_trend_chart(terms),
            'fmRatio' : get_mf_ratio_chart(terms),
            'mpOrgs' : get_mp_orgs_chart(terms),
            'avgAge' : get_avg_age_chart(terms),
            'avgGroups' : get_avg_groups(terms),
            'avgOrgsMP' : get_avg_groups_chart(terms),
            'absence' : get_absences_chart(terms),
            'polls' : get_poll_count_chart(terms),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'term' : TermOfOffice.objects.filter().order_by('-id')[0]
        },
        context_instance = RequestContext(request)
    )


@cache_page(60 * 60 * 24)
def term_tab(request, start, end):
    """
    Function term_tab(request, start, end)

    Implements django's view for page, which sums up single term in parliament.
    The mandatory arguments are as follows:
        request -   instance of django.http.HttpRequest class
        start   -   string with year value
        end     -   string with year value
    The arguments start, end are grabbed from URL, they define a particular
    term of office we want to generate page for.

    Returns instance of django.http.HttpResponse class.
    """
    term = TermOfOffice.get_term_or_404(start, end)
    totalPolls = 0
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    meetings = Meeting.objects.filter(term = term) 
    for m in meetings:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        totalPolls += Poll.objects.filter(meeting = m).count()

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    parliament = Group.objects.get(
                    type__iexact = 'PARLAMENT',
                    term = term
                )

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    vs = VoteStats.objects.getStatsForTerm(term)
    total = vs.totalAbsences + vs.presences
    if total == 0:
        total = 1
    total = total * 1.0

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dateStart = Poll.objects.filter(
                            meeting__term = term
                        ).order_by('date')[0].date
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dateEnd = Poll.objects.filter(
                            meeting__term = term
                        ).order_by('-date')[0].date

    return render_to_response(
        'single_term.html',
        {   'term' : term,
            'tabIndex' : 3,
            'dateStart' : dateStart,
            'dateEnd' : dateEnd,
            'date' : dateEnd,
            'terms' : term.getTermsList(),
            'totalPolls' : totalPolls,
            'totalMeetings' : meetings.count(),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'mpTotal' : PersonDetail.objects.filter(term = term).count(),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'orgCount' : Group.objects.filter(
                            term = term
                        ).count(),
            'avgAge' : parliament.getAvgAge(),
            'mpAge' : get_party_age(term),
            'absences' : '%.2f' % get_percents(vs.totalAbsences, total),
            'recycle' : get_recycled_pie_chart(term),
            'fmRatio' : parliament.getMfPie(),
            'mpClubs' : parliament.getPartyPie(),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'boards' : Group.objects.filter(
                                term = term,
                                type__iexact = u'VÝBOR'
                            ).order_by('origName'),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'committees' : Group.objects.filter(
                                term = term,
                                type__exact = u'KOMISE'
                            ).order_by('origName'),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'mpuGroups' : Group.objects.filter(
                                term = term,
                                type__regex = u'.*MPU'
                            ).order_by('origName'),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'delegs' : Group.objects.filter(
                                term = term,
                                type__exact = u'DELEGACE'
                            ).order_by('origName'),
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'rest' : Group.objects.filter(
                                Q(term = term),
                                ~Q(type__exact = u'DELEGACE'),
                                ~Q(type__regex = u'.*MPU'),
                                ~Q(type__iexact = u'KOMISE'),
                                ~Q(type__iexact = u'KLUB'),
                                ~Q(type__iregex = u'(POD)?VÝBOR')
                            ).order_by('origName'),
        },
        context_instance = RequestContext(request)
    )


@cache_page(60 * 60 * 24)
def index_html(request,
    year = None, month = None, day = None, rangeType = 'den'):
    """
    Function index_html(request,
        year = None, month = None, day = None, rangeType = 'den')
    
    Implements django view. It renders page, which sums up 'global data' for
    parliament like presences, absences, loyal MPs, rebels etc. The data are gathered
    for a particular range defined by parameters passed by URL. The arguments are
    as follows:
        request -   django.http.HttpRequest instance
        year, month, day    -   are optional parameters defining a day we want to
                                use as a base. The date of the last meeting is
                                assumed.
        rangeType   -   is a string. the expected vales are:
                            o   'den' for day range
                            o   'tyden' for week range. week is chosen by date,
                                the chosen week must include day defined by
                                year, month, day arguments
                            o   'mesic' for month range (month is chosen by
                                date, the chosen month must include the day
                                defined by year, month, day arguments.
                        the argument is optional, default value is 'den'
    The function uses index.html template

    Returns an instance of django.http.HttpResponse class.
    """
    #suppress 'too many local variables' warning
    #pylint: disable-msg=R0914
    #suppress 'too many statements' warning
    #pylint: disable-msg=R0915
    def getTop(list, getSortValue):
        """
        Nested function getTop(list, getSortValue)

        The function is part of index_html(). Function creates slice of
        'list'. There are two mandatory arguments:
            list -  is an ordered list of objects by certain key
            getSortValue    -   function which takes object as an argument
                                and returns an object's key.
        The slice will content objects, which have the same value of key
        as the first object in list.

        Returns a slice of list
        """
        #suppress 'redefining built-in' warning
        #pylint: disable-msg=W0622
        retVal = []
        first = list[0]
        aVal = getSortValue(first)
        for i in list:
            if aVal != getSortValue(i):
                break
            retVal.append(i)

        return retVal

    poll = None
    date = None
    if (year == None):
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        poll = Poll.objects.order_by('-date')[0]
        date = poll.date
    else:
        date = datetime.date(   year = int(year),
                                month = int(month),
                                day = int(day)
                        )
        poll = get_list_or_404(Poll, date = date)
        poll = poll[0]

    rangeData = create_range_data(date = date, rangeType = rangeType)

    pollCount = 0
    accepted = 0
    if rangeData['dateEnd'] == None:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        pollCount = Poll.objects.filter(
                        date = rangeData['dateStart']
                    ).count()
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        accepted = Poll.objects.filter(
                        date = rangeData['dateStart'],
						verdict__iexact = u'Přijato'
                    ).count()
    else:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        pollCount = Poll.objects.filter(
                        date__range = (
                            rangeData['dateStart'],
                            rangeData['dateEnd']
                        )
                    ).count()

        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        accepted = Poll.objects.filter(
                        date__range = (
                            rangeData['dateStart'],
                            rangeData['dateEnd']
                        ),
                        verdict__iexact = u'Přijato'
                    ).count()

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    votes = MpVote.objects.getDayStats(
        rangeData['dateStart'],
        rangeData['dateEnd']
    ).votes

    term = TermOfOffice.get_term_for_date(rangeData['dateStart'])

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    slackers = Person.objects.getSlackers(
        rangeData['dateStart'],
        rangeData['dateEnd']
    )
    slackerLimit = slackers[0].votes.totalAbsencesPerc
    slackerList = getTop(slackers, lambda s: s.votes.totalAbsences)
    for mp in slackerList:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        mp.detail = PersonDetail.objects.get(person = mp, term = term)
        mp.party = mp.getPartyClub(date)
        
    slackerList.sort(cmp_surname)

    slackers.reverse()
    beeList = getTop(slackers, lambda s: s.votes.totalAbsences)
    beeLimit = beeList[0].votes.totalAbsencesPerc
    for mp in beeList:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        try:
            mp.detail = PersonDetail.objects.get(person = mp, term = term)
        except ObjectDoesNotExist:
            mp.detail = None
        try:
            mp.party = mp.getPartyClub(rangeData['dateStart'])
        except ObjectDoesNotExist:
            mp.party = None
    
    beeList.sort(cmp_surname)

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    rebels = Person.objects.getRebels(
        dayStart = rangeData['dateStart'],
        dayEnd = rangeData['dateEnd'],
        desc = False
    )
    rebelLimit = rebels[0].accordance.diffPerc
    rebelList = getTop(rebels, lambda s: s.accordance.same)
    for r in rebelList:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        r.detail = PersonDetail.objects.get(person = r, term = term)
    rebelList.sort(cmp_surname)

    rebels.reverse()
    loyalMPs = rebels
    loyalLimit = loyalMPs[0].accordance.samePerc
    loyalList = getTop(loyalMPs, lambda s: s.accordance.same)
    for l in loyalList:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        l.detail = PersonDetail.objects.get(person = l, term = term)
    loyalList.sort(cmp_surname)
    
    rebels.reverse()
    rebels.sort(
        lambda a, b: int(
            (a.activeAccordance.samePerc - b.activeAccordance.samePerc) * 100
        )
    )
    activeRebels = rebels
    activeRebelLimit = activeRebels[0].activeAccordance.diffPerc
    activeRebelList = getTop(activeRebels, lambda s: s.activeAccordance.same)
    for r in activeRebelList:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        r.detail = PersonDetail.objects.get(person = r, term = term)
    activeRebelList.sort(cmp_surname)

    return render_to_response(
        'index.html',
        {   'poll' : poll,
            'year' : poll.date.year,
            'month' : poll.date.month,
            'pollCount' : pollCount,
            'accepted' : accepted,
            'refused' : pollCount - accepted,
            'absences' : '%.2f' % votes.totalAbsencesPerc,
            'presencePie' : MpVote.get_presence_pie(
                    rangeData['dateStart'],
                    rangeData['dateEnd']
            ),
            'slackerLimit' : '%.2f' % slackerLimit,
            'slackers' : slackerList,
            'slackerCount' : len(slackerList),
            'beeLimit' : '%.2f' % (100.0 - beeLimit),
            'bees' : beeList,
            'beeCount' : len(beeList),
            'rebelLimit' : '%.2f' % rebelLimit,
            'rebelCount' : len(rebelList),
            'rebels' : rebelList,
            'loyalLimit' : '%.2f' % loyalLimit,
            'loyalCount' : len(loyalList),
            'loyalList' : loyalList,
            'activeRebelLimit' : '%.2f' % activeRebelLimit,
            'activeRebelCount' : len(activeRebelList),
            'activeRebels' : activeRebelList,
            'term' : term,
            'viewTitle' : rangeData['viewTitle'],
            'date': date,
            'dateStart' : rangeData['dateStart'],
            'dateEnd' : rangeData['dateEnd'],
            'tabIndex' : rangeData['tabIndex'],
            'rangeType' : rangeType,
        },
        context_instance = RequestContext(request)
    )


def show_mp_term(request, mpSlug, start, end):
    """
    Function show_mp_term(request, mpSlug, start, end)

    Implements a djanog's view, which renders HTML page with data for
    particular MP (defined by mpSlug) and term (defined by start, end).  The
    mpSlug, start, end arguments are gathered from URL. All arguments
    are mandatory:
        request -   instance of django.http.HttpResponse class
        mpSlug  -   is string used as a slug/key to fetch MP from DB
        start   -   string which defines the start year of particular term
        end     -   string defininf end year of particular term
    Function uses mp_term_tab.html template.
    
    Returns an instance of django.http.HttpResponse class.
    """
    #suppress 'too many local variables' warning
    #pylint: disable-msg=R0914
    term = TermOfOffice.get_term_or_404(start = start, end = end)
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    mp = Person.objects.getPerson(person = mpSlug.lower(), term = term)
    
    if mp == None:
        raise Http404

    groupMemberships = mp.getGroups(term)
    dateStart = groupMemberships.order_by('start')[0].start
    dateEnd = None
    
    if groupMemberships.filter(end = None).count() != 0:
        dateEnd = datetime.date.today()
    else:
        dateEnd = groupMemberships.order_by('-end')[0].end

    mpParties = mp.getPartyMships(term)
    presenceChart = mp.votes.getPresenceChart()
    presenceChart.title(
        _(u'Absence %s %s (%s %s)' %
            (   mp.name,
                mp.surname,
                term.getStart(),
                term.getEnd()
            )
        )
    )
    presenceChart.size(430, 120)

    group = None
    groupSlug = ''
    try:
        groupSlug = request.GET.get('accordGroup')
        group = Group.objects.get(slug = groupSlug)
    except (ObjectDoesNotExist, KeyError):
        group = mp.getPartyClub(dateEnd)

    accordance, activeAccordance = mp.getAccordanceCharts(
        group = group,
        dateStart = dateStart,
        dateEnd = dateEnd
    )

    partyPie = None
    if group.type != 'KLUB':
        partyPie = group.getPartyPie()
        partyPie.size(330, 80)

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    lastMeetingInTerm = Poll.objects.filter(
        meeting__term = term
    ).order_by('-date')[0].date

    return render_to_response(
        'mp_term_tab.html', 
        {   'extendedTitle' : '[ %s - %s ]' % (term.getStart(), term.getEnd()),
            'term' : term,
            'date' : lastMeetingInTerm,
            'dateStart': dateStart,
            'dateEnd' : dateEnd,
            'terms' : mp.getTermLinks(term),
            'mp' : mp,
            'mships' : groupMemberships,
            'partyClubs' : mpParties,
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'parties' : Group.objects.filter(
                ~Q(id = mpParties[0].group.id),
                term = term,
                type__iexact = 'KLUB'
            ),
            'justiceKey' : getAuthToken(mp.name + mp.surname),
            'presenceChart': presenceChart,
            'accordanceChart' : accordance,
            'activeAccordance' : activeAccordance,
            'tabIndex' : 3,
            'accordGroupSlug' : groupSlug,
            'partyPie' : partyPie,
            'noActive' : 0,
        },
        context_instance = RequestContext(request)
    )

@cache_page(60 * 60 * 24)
#pylint: disable-msg=R0913
def show_mp_days(request, mpSlug, rangeType, year, month, day):
    """
    Function show_mp_days(request, mpSlug, rangeType, year, month, day)

    Implements a django view, which renders page with data for date range
    and particular MP. All arguments are mandatory:
        request -   instance of django.http.HttpResponse class
        mpSlug  -   slug string referencing particular MP in DB
        rangeType   -   is a string. the expected vales are:
                            o   'den' for day range
                            o   'tyden' for week range. week is chosen by date,
                                the chosen week must include day defined by
                                year, month, day arguments
                            o   'mesic' for month range (month is chosen by
                                date, the chosen month must include the day
                                defined by year, month, day arguments.
                        the argument is optional, default value is 'den'
        year, month, day    -   are strings, which are defining a particular
                                date.
    Function uses mp_dwm_tab.html template (MP day week month).

    Returns django.http.HttpResponse instance
    """
    #suppress 'too many local variables' warning
    #pylint: disable-msg=R0914
    date = datetime.date(
        year = int(year),
        month = int(month),
        day = int(day)
    )

    mp = get_object_or_404(Person, slug = mpSlug.lower())

    rangeData = create_range_data(date, rangeType)
    if rangeData == None:
        raise Http404

    groupMemberships = mp.getMshipsForDateRange(
        dateStart = rangeData['dateStart'],
        dateEnd = rangeData['dateEnd']
    )
    groupMemberships.query.group_by = ['group_id']
        
    mpParties = groupMemberships.filter(group__type = 'KLUB')
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dayStats = MpDayStats.objects.getStatsForRange(
        mp = mp,
        dateStart = rangeData['dateStart'],
        dateEnd = rangeData['dateEnd']
    )
    presenceChart = dayStats.votes.getPresenceChart()
    presenceChart.title(
        _(u'Absence %s %s (%s)' %
            (
                mp.name,
                mp.surname,
                rangeData['chartTitle']
            )
        )
    )
    presenceChart.size(430, 120)

    group = None
    groupSlug = ''
    try:
        groupSlug = request.GET.get('accordGroup')
        group = Group.objects.get(slug = groupSlug)
    except (ObjectDoesNotExist, KeyError):
        group = mp.getPartyClub(rangeData['dateStart'])

    accordance, activeAccordance = mp.getAccordanceCharts(
        group = group,
        dateStart = rangeData['dateStart'],
        dateEnd = rangeData['dateEnd']
    )

    noActive = 0
    if dayStats.votes.totalAbsencesPerc == 100.0:
        activeAccordance = None
        # we need to pass it to template, template will remember there are no
        # meaingful data for activeAccordance. it will instruct the json view
        # function (get_mp_accordance) not to generate activeAccordance chart.
        noActive = 1
        
    partyPie = None
    if group.type != 'KLUB':
        partyPie = group.getPartyPie(
            rangeData['dateStart'],
            rangeData['dateEnd']
        )
        partyPie.size(330, 80)

    poll = None
    if rangeData['dateEnd'] == None:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        poll = Poll.objects.filter(date = rangeData['dateStart'])[0]
    else:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        poll = Poll.objects.filter(
            date__range = (rangeData['dateStart'], rangeData['dateEnd'])
        ).order_by('-date')[0]
            
    term = poll.meeting.term
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    mp.detail = PersonDetail.objects.get(person = mp, term = term)
    mp.votes = dayStats.votes

    return render_to_response(
        'mp_dwm_tab.html',
        {   'extendedTitle' : '- ' + rangeData['viewTitle'],
            'term' : term,
            'date' : poll.date,
            'dateStart': rangeData['dateStart'],
            'dateEnd' : rangeData['dateEnd'],
            'mp' : mp,
            'mships' : groupMemberships,
            'partyClubs' : mpParties,
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'parties' : Group.objects.filter(
                ~Q(id = mpParties[0].group.id),
                term = term,
                type__iexact = 'KLUB'
            ),
            'justiceKey' : getAuthToken(unicode(mp.name) + unicode(mp.surname)),
            'presenceChart': presenceChart,
            'accordanceChart' : accordance,
            'activeAccordance' : activeAccordance,
            'tabIndex' : rangeData['tabIndex'],
            'accordGroupSlug' : groupSlug,
            'partyPie' : partyPie,
            'rangeType' : rangeType,
            'noActive' : noActive
        },
        context_instance = RequestContext(request)
    )


def show_poll(request, pollId):
    """
    Function show_poll(request, pollId)

    Function renders page with broken down results for single poll
    in parliament. The arguments are:
        request -   instance of django.http.HttpRequest
        pollId  -   string with poll id, which is the same ID as
                    poll ID at official pages psp.cz
    Function uses show_poll.html template.

    Returns instance of django.http.HttpResponse class
    """
    poll = get_object_or_404(Poll, pollId = pollId)
    term = poll.meeting.term

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    parties = Group.objects.getGroupWithStats(
        term,
        Q(type__iexact = 'KLUB'),
        poll
    )
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    boards = Group.objects.getGroupWithStats(
        term,
        Q(type__iexact = u'VÝBOR'),
        poll
    )
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    mpu = Group.objects.getGroupWithStats(
        term,
        Q(type__regex = u'.*MPU'),
        poll
    )
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    delegs = Group.objects.getGroupWithStats(
        term,
        Q(type__iexact = u'DELEGACE'),
        poll
    )
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    comms = Group.objects.getGroupWithStats(
        term,
        Q(type__iexact = u'KOMISE'),
        poll
    )
    qObjs = (
        Q(term = poll.meeting.term),
        ~Q(type__iexact = u'VLÁDA'),
        ~Q(type__exact = u'DELEGACE'),
        ~Q(type__regex = u'.*MPU'),
        ~Q(type__iexact = u'KOMISE'),
        ~Q(type__iexact = u'KLUB'),
        ~Q(type__iregex = u'(POD)?VÝBOR'),
        ~Q(type__iregex = u'PARLAMENT')
    )
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    rest = Group.objects.getGroupWithStatsArg(poll, qObjs)

    rebels = poll.getRebels()
    activeRebels = poll.getRebels(active = True)
    
    rebels.sort(cmp_surname)
    activeRebels.sort(cmp_surname)

    return render_to_response(
        'show_poll.html',
        {   'pie' : poll.resultPie(),
            'poll' : poll,
            'rebels' : rebels,
            'activeRebels' : activeRebels,
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'slackers' : MpVote.objects.filter(
                        result__iregex = '[^ANZ]',
                        poll = poll
                    ).order_by('person__surname'),
            'year' : poll.date.year,
            'month' : poll.date.month,
            'partyClubs' : parties,
            'boards' : boards,
            'mpuGroups' : mpu,
            'delegs' : delegs,
            'committees' : comms,
            'rest' : rest,
            #suppress 'no objects member' warning
            #pylint: disable-msg=E1101
            'parlament' : Group.objects.get( type = u'PARLAMENT', term = term),
        },
        context_instance = RequestContext(request)
    )


def get_group_types(group):
    """
    Function get_group_types(group)

    Function returns the list of groups grouped by group.type. The mandatory
    parameter group is instance of psp.models.Group class.

    Returns list of psp.models.Group instances, each instance is extended
    by attribute 'groups', which is a list of another groups with same
    attribute 'type' value.
    """
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    groupTypes = Group.objects.filter(  ~Q(id = group.id),
                                        term = group.term
                                    )
    groupTypes.query.group_by = ['type']

    retVal = []
    for g in groupTypes:
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        g.groups = Group.objects.filter(    ~Q(id = group.id),
                                            term = group.term,
                                            type = g.type
                                    )
        retVal.append(g)
    
    return retVal


@cache_page(60 * 60 * 24)
def show_group_term(request, groupSlug):
    """
    Function show_group_term(request, groupSlug)
    
    Function renders a html page with sumary data for particular group. The
    group is references by its slug. The arguments are as follows:
        request -   instance of django.http.HttpRequest class
        groupSlug   -   string with group slug
    Function uses group_view.html template.

    Returns django.http.HttpResponse instance
    """
    group = get_object_or_404(Group, slug = groupSlug.lower())
    partyPie = None
    if group.type != 'KLUB':
        partyPie = group.getPartyPie()

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dateStart = Poll.objects.filter(
        meeting__term = group.term
    ).order_by('date')[0].date
    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    dateEnd = Poll.objects.filter(
        meeting__term = group.term
    ).order_by('-date')[0].date
    group = group.getGroupConsistency(dateStart = dateStart, dateEnd = dateEnd)
    disciplinePie = group.consistency.getChart()
    disciplinePie.title(    _(u'Disciplina %s (%s - %s)') % (   
                                    group.name,
                                    group.term.getStart(),
                                    group.term.getEnd()
                                )
                        )
    disciplinePie.size(330, 80)

    #suppress 'no objects member' warning
    #pylint: disable-msg=E1101
    poll = Poll.objects.filter(
        meeting__term = group.term
    ).order_by('-date')[0]

    accordPartyPie = None
    accordChart = None
    #suppress 'Exception does not do anything' warning
    #pylint: disable-msg=W0704
    try:
        groupSlug = request.GET.get('accordGroup')
        otherGroup = Group.objects.get(slug = groupSlug)
        if otherGroup.type != 'KLUB':
            partyPie = group.getPartyPie()
            partyPie.size(330, 80)
        accordChart = group.getAccordanceWithGroup(
            otherGroup,
            dateStart = dateStart,
            dateEnd = dateEnd
        )
    except (ObjectDoesNotExist, KeyError):
        pass

    return render_to_response(
        'group_view.html',
        {
            'group' : group,
            'date' : poll.date,
            'absencesPie' : group.getPresencePieChart(),
            'memberCount' : len(group.getMembersByName()),
            'avgAge' : group.getAvgAge(),
            'partyPie' : partyPie,
            'disciplinePie' : disciplinePie,
            'tabIndex' : 3,
            'groupTypes' : get_group_types(group),
            'accordanceChart' : accordChart,
            'accordPartyPie' : accordPartyPie,
        },
        context_instance = RequestContext(request)
    )


@cache_page(60 * 60 * 24)
def show_group_range(request, groupSlug, rangeType, year, month, day):
    """
    Function show_group_range(request,
        groupSlug, rangeType, year, month, day)

    Function renders data for particular group and date (or date range).
    All arguments are mandatory:
        request -   an instance of django.http.HttpResponse class
        groupSlug   -   string definging a particular group
        rangeType   -   is a string. the expected vales are:
                            o   'den' for day range
                            o   'tyden' for week range. week is chosen by date,
                                the chosen week must include day defined by
                                year, month, day arguments
                            o   'mesic' for month range (month is chosen by
                                date, the chosen month must include the day
                                defined by year, month, day arguments.
        year, month, day    -   are defining a date
    Function uses group_view.html template.

    Returns django.http.HttpResponse object
    """
    date = datetime.date(
            year = int(year),
            month = int(month),
            day = int(day)
        )
    rangeData = create_range_data(date, rangeType)
    group = get_object_or_404(Group, slug = groupSlug.lower())
    memberCount = len(
        group.getMembersByName(
            dateStart = rangeData['dateStart'],
            dateEnd = rangeData['dateEnd']
        )
    )

    if group.type != 'KLUB':
        partyPie = group.getPartyPie(
            dateStart = rangeData['dateStart'],
            dateEnd = rangeData['dateEnd']
        )
    else:
        partyPie = None

    group = group.getGroupConsistency(
        dateStart = rangeData['dateStart'],
        dateEnd = rangeData['dateEnd']
    )
    disciplinePie = group.consistency.getChart()
    disciplinePie.title(    _(u'Disciplina %s (%s)') % (    
                                    group.name,
                                    rangeData['chartTitle']
                                )
                        )
    disciplinePie.size(330, 80)

    accordPartyPie = None
    accordChart = None
    #suppress 'Exception does not do anything' warning
    #pylint: disable-msg=W0704
    try:
        groupSlug = request.GET.get('accordGroup')
        otherGroup = Group.objects.get(slug = groupSlug)
        if otherGroup.type != 'KLUB':
            accordPartyPie = group.getPartyPie(
                dateStart = rangeData['dateStart'],
                dateEnd = rangeData['dateEnd']
            )
            accordPartyPie.size(330, 80)
        accordChart = group.getAccordanceWithGroup(
            otherGroup,
            dateStart = rangeData['dateStart'],
            dateEnd = rangeData['dateEnd']
        )
    except (ObjectDoesNotExist, KeyError):
        pass

    date = None
    if (rangeData['dateEnd'] != None):
        #suppress 'no objects member' warning
        #pylint: disable-msg=E1101
        date = Poll.objects.filter(
            date__range = (rangeData['dateStart'], rangeData['dateEnd'])
        ).order_by('-date')[0].date
    else:
        date = rangeData['dateStart']

    return render_to_response(
        'group_view.html',
        {   'absencesPie' : group.getPresencePieChart(
                rangeData['dateStart'],
                rangeData['dateEnd']
            ),
            'date' : date,
            'group' : group,
            'memberCount' : memberCount,
            'avgAge' : group.getAvgAge(),
            'partyPie' : partyPie,
            'disciplinePie' : disciplinePie,
            'tabIndex' : rangeData['tabIndex'],
            'groupTypes' : get_group_types(group),
            'rangeType' : rangeType,
            'accordanceChart' : accordChart,
            'accordPartyPie' : accordPartyPie, 
        },
        context_instance = RequestContext(request)
    )



def show_group(request, groupSlug, rangeType = None,
    year = None, month = None, day = None):
    """
    Function show_group(requst, groupSlu, rangeType = None, year = None,
        month = None, day = None) 

    Function implements django view. Depending on arguments gathered from URL
    it calls either psp.views.show_group_term() function or
    psp.views.show_group_range(). The arguments are as follows:
        request -   mandatory argument is instance of django.http.HttpRequest
        groupSlug   -   string slug defining particular group
        rangeType   -   is a string. the expected vales are:
                            o   'den' for day range
                            o   'tyden' for week range. week is chosen by date,
                                the chosen week must include day defined by
                                year, month, day arguments
                            o   'mesic' for month range (month is chosen by
                                date, the chosen month must include the day
                                defined by year, month, day arguments.
                        rangeType is optional argument
        year, month, day    -   are defining a date, all these are optional
        
    If no optional argument is defined the function will use
    psp.views.show_group_term() to render page. If there are optional arguments
    defined, then function will use psp.views.show_group_range() to render a
    page.

    Returns an instance of django.http.HttpResponse instance.
    """

    if rangeType == None:
        return show_group_term(request, groupSlug)
    else:
        return show_group_range(
            request,
            groupSlug,
            rangeType,
            year,
            month,
            day
        )


@cache_page(60 * 60 * 24)
def show_mp_by_mp_id(request, mpId):
    """
    Function show_mp_by_mp_id(request, mpId)

    Function renders mp_dwm_tab.html view for particular MP referred by MP's ID
    from psp.cz. The MP profile is rendered by the recent MP's poll results.

    The URL makes live of external pages easier, since they need to know mpId.

    Returns an instace of django.http.HttpResponse instance
    """

    mp = get_object_or_404(Person, mpId = mpId)
    p = Poll.objects.all().order_by('-date')[0]
    return show_mp_days(
            request, mp.slug, 'den',
            str(p.date.year), str(p.date.month), str(p.date.day)
        )
